package com.graduation.sports.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.navigation.NavigationView;
import com.graduation.sports.R;
import com.graduation.sports.base.BaseActivity;
import com.graduation.sports.bean.EveryDaySteps;
import com.graduation.sports.config.Session;
import com.graduation.sports.ui.fragment.CommunityFragment;
import com.graduation.sports.ui.fragment.FoundFragment;
import com.graduation.sports.ui.fragment.MeFragment;
import com.graduation.sports.ui.fragment.TrainingFragment;
import com.graduation.sports.util.AppManager;
import com.graduation.sports.util.DateUtils;

import org.litepal.LitePal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by apc_allen
 * date : 2/16/21
 * description :
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, SensorEventListener {
    private LinearLayout tabTrain;
    private LinearLayout tabFound;
    private LinearLayout tabCommunity;
    private LinearLayout tabMe;

    private ImageView icoTrain;
    private ImageView icoFound;
    private ImageView icoCommunity;
    private ImageView icoMe;

    private TextView txtTrain;
    private TextView txtFound;
    private TextView txtCommunity;
    private TextView txtMe;
    private TextView tvName;
    private TextView tvRanking;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;//滑动菜单

    private NavigationView navView;

    private TrainingFragment trainingFragment;
    private FoundFragment foundFragment;
    private CommunityFragment communityFragment;
    private MeFragment meFragment;
    private long mExitTime;

    SensorManager mSensorManager;//管理器实例
    Sensor stepCounter;//传感器
    float mSteps;//截止当天0点时步数/重启手机到当前为止的步数

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initDataAndEvent(Bundle savedInstanceState) {
        initView();
//        initStep();


    }

    private void initStep(){
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        stepCounter = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (stepCounter != null) {
            mSensorManager.registerListener(this, stepCounter, mSensorManager.SENSOR_DELAY_GAME);
        } else {
            ToastUtils.showShort("未找到计步传感器");
        }
    }

    private void initView(){
        tabTrain = findView(R.id.bottom_train);
        tabFound = findView(R.id.bottom_found);
        tabCommunity = findView(R.id.bottom_community);
        tabMe = findView(R.id.bottom_me);

        icoTrain = findView(R.id.bottom_ico_train);
        icoFound = findView(R.id.bottom_ico_found);
        icoCommunity = findView(R.id.bottom_ico_community);
        icoMe = findView(R.id.bottom_ico_me);

        txtTrain = findView(R.id.bottom_txt_train);
        txtFound = findView(R.id.bottom_txt_found);
        txtCommunity = findView(R.id.bottom_txt_community);
        txtMe = findView(R.id.bottom_txt_me);


        navView = findView(R.id.nav_view);
        navView.setNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.ranking){
                ToastUtils.showShort("运动排名");
            }
            if (id == R.id.diary){
                startActivity(new Intent(MainActivity.this, DiaryActivity.class));
            }
            if (id == R.id.discuss){
                ToastUtils.showShort("运动讨论");
            }
            if (id == R.id.course){
                ToastUtils.showShort("运动课讯");
            }

            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        });

        View headerView = navView.getHeaderView(0);
        tvName = headerView.findViewById(R.id.tv_name);
        tvRanking = headerView.findViewById(R.id.tv_ranking);
        tvName.setText(Session.getUserInfo().getUserName());
        tvRanking.setText("全校排名：158");
        tvRanking.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort("goto ranking");
            }
        });

        tabTrain.setOnClickListener(this);
        tabFound.setOnClickListener(this);
        tabCommunity.setOnClickListener(this);
        tabMe.setOnClickListener(this);

        trainingFragment = new TrainingFragment();
        foundFragment = new FoundFragment();
        communityFragment = new CommunityFragment();
        meFragment = new MeFragment();

        refreashFragment(R.id.bottom_train);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_train:
                changeTabState(R.id.bottom_train);
                refreashFragment(R.id.bottom_train);
                break;
            case R.id.bottom_found:
                changeTabState(R.id.bottom_found);
                refreashFragment(R.id.bottom_found);
                break;
            case R.id.bottom_community:
                changeTabState(R.id.bottom_community);
                refreashFragment(R.id.bottom_community);
                break;
            case R.id.bottom_me:
                changeTabState(R.id.bottom_me);
                refreashFragment(R.id.bottom_me);
                break;
        }
    }


    @OnClick({R.id.titleText})
    public void onClickView(View view){
        int id = view.getId();
        if (id == R.id.titleText) {
            drawerLayout.openDrawer(GravityCompat.START);
        }
    }
    private void changeTabState(int tabId) {
        if (tabId == R.id.bottom_train) {
            icoTrain.setImageResource(R.mipmap.icon_train_pressed);
            txtTrain.setTextColor(getResources().getColor(R.color.basecolor));
        } else {
            icoTrain.setImageResource(R.mipmap.icon_train_unpressed);
            txtTrain.setTextColor(getResources().getColor(R.color.bottom_tab_normal));
        }
        if (tabId == R.id.bottom_found) {
            icoFound.setImageResource(R.mipmap.icon_found_pressed);
            txtFound.setTextColor(getResources().getColor(R.color.basecolor));
        } else {
            icoFound.setImageResource(R.mipmap.icon_found_unpressed);
            txtFound.setTextColor(getResources().getColor(R.color.bottom_tab_normal));
        }
        if (tabId == R.id.bottom_community) {
            icoCommunity.setImageResource(R.mipmap.icon_community_pressed);
            txtCommunity.setTextColor(getResources().getColor(R.color.basecolor));
        } else {
            icoCommunity.setImageResource(R.mipmap.icon_community_unpressed);
            txtCommunity.setTextColor(getResources().getColor(R.color.bottom_tab_normal));
        }
        if (tabId == R.id.bottom_me) {
            icoMe.setImageResource(R.mipmap.icon_me_pressed);
            txtMe.setTextColor(getResources().getColor(R.color.basecolor));
        } else {
            icoMe.setImageResource(R.mipmap.icon_me_unpressed);
            txtMe.setTextColor(getResources().getColor(R.color.bottom_tab_normal));
        }
    }

    private void refreashFragment(int btnId) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (btnId) {
            case R.id.bottom_train:
                transaction.replace(R.id.fragment_container, trainingFragment);
                break;
            case R.id.bottom_found:
                transaction.replace(R.id.fragment_container, foundFragment);
                break;
            case R.id.bottom_community:
                transaction.replace(R.id.fragment_container, communityFragment);
                break;
            case R.id.bottom_me:
                transaction.replace(R.id.fragment_container, meFragment);
                break;
        }
        transaction.commit();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 800) {
                ToastUtils.showShort("再按一次退出运动");
                mExitTime = System.currentTimeMillis();
                return true;
            } else {
                AppManager.getInstance().killAllActivity();
                AppManager.getInstance().AppExit(this);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        List<EveryDaySteps> everyDayStepsList = LitePal.findAll(EveryDaySteps.class);
        String today = DateUtils.getOldDate(0);
        if (everyDayStepsList.size() == 0) {
            EveryDaySteps everyDaySteps = new EveryDaySteps();
            everyDaySteps.setSteps(sensorEvent.values[0]);
            everyDaySteps.setToday(today);
            everyDaySteps.setTodaysteps(0.0f);
            insertOrUpdateSteps(everyDaySteps);

            mSteps = sensorEvent.values[0];
        } else {
            if (sensorEvent.values[0] < everyDayStepsList.get(0).getSteps()) {
                LitePal.deleteAll(EveryDaySteps.class, "today = ?", DateUtils.getOldDate(0));

                EveryDaySteps everyDaySteps = new EveryDaySteps();
                everyDaySteps.setSteps(sensorEvent.values[0]);
                everyDaySteps.setToday(today);
                everyDaySteps.setTodaysteps(0);
                insertOrUpdateSteps(everyDaySteps);

                mSteps = sensorEvent.values[0];
            } else {
                mSteps = everyDayStepsList.get(0).getSteps();
            }
        }

        float showSteps = sensorEvent.values[0] - mSteps;
        EveryDaySteps everyDaySteps = new EveryDaySteps();
        everyDaySteps.setSteps(mSteps);
        everyDaySteps.setToday(today);
        everyDaySteps.setTodaysteps(showSteps);
        insertOrUpdateSteps(everyDaySteps);
        String time = "00:00:00";
        if (time.equals(new SimpleDateFormat("HH:mm:ss").format(new Date()))){
            EveryDaySteps steps = new EveryDaySteps();
            steps.setSteps(sensorEvent.values[0]);
            steps.setToday(today);
            steps.setTodaysteps(showSteps);
            insertOrUpdateSteps(steps);
            mSteps = sensorEvent.values[0];
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        initStep();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void insertOrUpdateSteps(EveryDaySteps everyDaySteps){
        if (LitePal.isExist(EveryDaySteps.class, "today = ?", everyDaySteps.getToday())){
            ContentValues values = new ContentValues();
            values.put("steps", everyDaySteps.getSteps());
            values.put("todaysteps", everyDaySteps.getTodaysteps());
            int result = LitePal.updateAll(EveryDaySteps.class, values, "today = ?",everyDaySteps.getToday());
        } else {
            everyDaySteps.save();
        }
    }
}
